from datetime import datetime
from odoo import fields, models, api
from odoo.exceptions import UserError
from odoo.addons.rp_courier_management.models.primary.rp_courier_mail_route import EXPRESS_CATEGORY
from ...functions.ship_order_fc import ShipOrderFC


class RPAvailableShipperMailRouteTran(models.TransientModel):
    _name = 'rp.available.shipper.mail.route.tran'
    _description = "可用托运商邮路"
    _rec_name = 'rp_asmr_code'

    def _default_auto_rp_asmr_code(self):
        records = self.env['rp.available.shipper.mail.route.tran'].search([])
        return "RP_ASMR" + str(len(records) + 1).zfill(3)

    rp_asmr_code = fields.Char(string='索引码', default=_default_auto_rp_asmr_code, index=True, copy=False, readonly=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    shipper_mail_route_id = fields.Many2one(string='托运商邮路', comodel_name='rp.shipper.mail.route')

    express_category = fields.Selection(string='发件类型', selection=EXPRESS_CATEGORY)
    same_city_flag = fields.Boolean(string='同城', copy=False)
    same_province_flag = fields.Boolean(string='同省', copy=False)
    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper')
    actual_weight = fields.Float(string='包裹实际重量', digits=(8, 3), default=0)
    rounded_weight = fields.Float(string='包裹取整重量', digits=(8, 3), default=0)

    aging_id = fields.Many2one(string='时效', comodel_name='rp.aging')
    expect_arrive_date = fields.Date(string='预计到达时间')
    tag_price = fields.Float(string='标价', digits=(8, 3), default=0)
    sale_adjusted_price = fields.Float(string='销售调后价', digits=(8, 3), default=0)

    used_sale_price_adjust_ids = fields.Many2many(string='使用销售调价', comodel_name='rp.shipper.sale.price.adjustment', readonly=True,
                                                  relation='rp_asmr_and_sale_price_adjustment_rel', column1='asmr_id', column2='sale_price_adjustment_id')

    def action_rewrite_smr(self):
        records = self.browse(self.env.context.get('active_ids'))

        # 判断同城，同省限制条件
        same_city, same_province = False, False
        send_postal_code = self.env['rp.postal.code'].browse(self.env.context.get('send_postal_code'))
        receive_postal_code = self.env['rp.postal.code'].browse(self.env.context.get('receive_postal_code'))
        if send_postal_code.id == receive_postal_code.id:
            same_city = True
        else:
            if send_postal_code.state_id.id == receive_postal_code.state_id.id:
                same_province = True
        if len(records) > 1:
            raise UserError('只能选择一条邮路')
        if records[0].same_city_flag and not same_city:
            raise UserError('此邮路仅适用于同城条件')
        elif records[0].same_province_flag and not same_province:
            raise UserError('此邮路仅适用于同省条件')

        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))
        ship_order.write({'shipper_mail_route_id': records.shipper_mail_route_id.id,
                          'shipper_id': records.shipper_id.id,
                          'aging_id': records.aging_id.id,
                          'used_sale_price_adjust_ids': [(6, 0, records.used_sale_price_adjust_ids.ids)],
                          'parcel_actual_weight': records.actual_weight,
                          'express_category': records.express_category,
                          'same_city_flag': records.same_city_flag,
                          'same_province_flag': records.same_province_flag,
                          'parcel_rounded_weight': records.rounded_weight,
                          'mail_route_tag_price': records.tag_price,
                          'mail_route_sale_adjusted_price': records.sale_adjusted_price,
                          'expect_arrive_date': records.expect_arrive_date})
